package com.sky.sky_server.controller.admin;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sky.sky_common.constant.MessageConstant;
import com.sky.sky_common.result.Result;
import com.sky.sky_common.util.AliossService;

import lombok.extern.slf4j.Slf4j;

@RestController("adminCommonController")
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {
    
    @Autowired
    private AliossService aliossService;

    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        if(file == null)
            return Result.error(MessageConstant.FILE_UPLOAD_NULL_ERROR);
        try{
            // 提取文件后缀名
            String fileName = file.getOriginalFilename();
            String suffix = ".png";
            if(fileName != null && fileName.contains(".")){
                suffix = fileName.substring(fileName.lastIndexOf("."));
            }
            // 转换为uuid
            String uuid = UUID.randomUUID().toString();
            String newFileName = uuid + suffix;

            // 上传文件
            String url = aliossService.uploadFileAndGetUrl(newFileName, file.getBytes());

            return Result.success(url);
        }catch (Exception e){
            log.error("文件上传失败");
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
